package cn.npe2.scaffolding.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * JavaBean Builder通用工具类
 *
 * @param <T>
 * @author: yic
 * @since: 2021-01-22 17:32
 **/

public class BuilderUtil<T> {

    private final Supplier<T> instantiate;
    private List<Consumer<T>> modifiers = new ArrayList<>();

    public BuilderUtil(Supplier<T> instantiator) {
        this.instantiate = instantiator;
    }

    public static <T> BuilderUtil<T> of(Supplier<T> instantiator) {
        return new BuilderUtil<>(instantiator);
    }

    public <P1> BuilderUtil<T> with(Consumer1<T, P1> consumer, P1 p1) {
        Consumer<T> c = instance -> consumer.accept(instance, p1);
        modifiers.add(c);
        return this;
    }

    public <P1, P2> BuilderUtil<T> with(Consumer2<T, P1, P2> consumer, P1 p1, P2 p2) {
        Consumer<T> c = instance -> consumer.accept(instance, p1, p2);
        modifiers.add(c);
        return this;
    }

    public <P1, P2, P3> BuilderUtil<T> with(Consumer3<T, P1, P2, P3> consumer, P1 p1, P2 p2,
            P3 p3) {
        Consumer<T> c = instance -> consumer.accept(instance, p1, p2, p3);
        modifiers.add(c);
        return this;
    }

    public T build() {
        T value = instantiate.get();
        modifiers.forEach(modifier -> modifier.accept(value));
        modifiers.clear();
        return value;
    }

    /**
     * 单个参数
     *
     * @param <T>
     * @param <P1>
     */
    @FunctionalInterface
    public interface Consumer1<T, P1> {

        void accept(T t, P1 p1);
    }

    /**
     * 两个参数，适用于内部类
     *
     * @param <T>
     * @param <P1>
     * @param <P2>
     */
    @FunctionalInterface
    public interface Consumer2<T, P1, P2> {

        void accept(T t, P1 p1, P2 p2);
    }

    /**
     * 三个参数，适用于内部类
     *
     * @param <T>
     * @param <P1>
     * @param <P2>
     * @param <P3>
     */
    @FunctionalInterface
    public interface Consumer3<T, P1, P2, P3> {

        void accept(T t, P1 p1, P2 p2, P3 p3);
    }

    /* 根据自定义参数定制化补充 */

}
